package com.ruoyi.web.controller.train;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.train.domain.*;
import com.ruoyi.train.service.*;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.K;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 培训课程信息Controller
 *
 * @author ruoyi
 * @date 2024-04-03
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/training/school/course")
public class JyTrainingSchoolCourseController extends BaseController {
    private final IJyTrainingSchoolService jyTrainingSchoolService;
    private final IJyTrainingSchoolCourseService jyTrainingSchoolCourseService;
    private final IJyTrainingSchoolCourseOutlineService jyTrainingSchoolCourseOutlineService;

    private final IJyTrainingSchoolCourseMaterialService jyTrainingSchoolCourseMaterialService;
    private final IJyTrainingSchoolCourseMaterialSpecsService jyTrainingSchoolCourseMaterialSpecsService;

    /**
     * 查询培训课程信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:course:list')")
    @GetMapping("/list")
    public TableDataInfo list(JyTrainingSchoolCourse jyTrainingSchoolCourse) {
        startPage();
        jyTrainingSchoolCourse.setDelFlag("0");
        List<JyTrainingSchoolCourse> list = jyTrainingSchoolCourseService.selectJyTrainingSchoolCourseList(jyTrainingSchoolCourse);

        if (CollectionUtil.isNotEmpty(list)) {
            List<Long> ids = CollStreamUtil.toList(list, JyTrainingSchoolCourse::getTrainingSchoolId);
            List<JyTrainingSchool> trainingSchools = jyTrainingSchoolService.selectJyTrainingSchoolByIds(ids);
            Map<Long, JyTrainingSchool> schoolMap = CollStreamUtil.toIdentityMap(trainingSchools, JyTrainingSchool::getId);

            list.forEach(v -> {
                JyTrainingSchool trainingSchool = schoolMap.get(v.getTrainingSchoolId());
                if (trainingSchool != null) {
                    v.setTrainingSchoolName(trainingSchool.getSchoolName());
                }
            });
        }

        return getDataTable(list);
    }

    /**
     * 导出培训课程信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:course:export')")
    @Log(title = "培训课程信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, JyTrainingSchoolCourse jyTrainingSchoolCourse) throws IOException {
        List<JyTrainingSchoolCourse> list = jyTrainingSchoolCourseService.selectJyTrainingSchoolCourseList(jyTrainingSchoolCourse);

        // Step.3 调用AutoPoi导出Excel
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String sheetName = "培训课程信息数据";
        String fileName = URLUtil.encode(sheetName).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), JyTrainingSchoolCourse.class).sheet(sheetName).doWrite(list);
    }

    /**
     * 获取培训课程信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:course:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        JyTrainingSchoolCourse schoolCourse = jyTrainingSchoolCourseService.selectJyTrainingSchoolCourseById(id);

        if (null != schoolCourse && null != schoolCourse.getTrainingSchoolId()) {
            JyTrainingSchool trainingSchool = jyTrainingSchoolService.selectJyTrainingSchoolById(schoolCourse.getTrainingSchoolId());
            if (trainingSchool != null) {
                schoolCourse.setTrainingSchoolName(trainingSchool.getSchoolName());
            }
        }
        
        Long courseId = schoolCourse.getId();

        JSONObject schoolCourseJson = JSONObject.from(schoolCourse);

        // 处理大纲
        List<JyTrainingSchoolCourseOutline> outlines = jyTrainingSchoolCourseOutlineService.selectJyTrainingSchoolCourseOutlineByCourseId(courseId);
        schoolCourseJson.put("courseOutlineList", outlines);

        // 处理 耗材/设备/教材
        List<JyTrainingSchoolCourseMaterial> courseMaterials = jyTrainingSchoolCourseMaterialService.selectJyTrainingSchoolCourseMaterialByCourseId(courseId);
        if (CollectionUtil.isNotEmpty(courseMaterials)) {
            List<JyTrainingSchoolCourseMaterialSpecs> courseMaterialSpecs = jyTrainingSchoolCourseMaterialSpecsService.selectJyTrainingSchoolCourseMaterialSpecsByCourseId(courseId);
            Map<Long, List<JyTrainingSchoolCourseMaterialSpecs>> materialSpecsMap = CollStreamUtil.groupByKey(courseMaterialSpecs, JyTrainingSchoolCourseMaterialSpecs::getMaterialId);

            List<JSONObject> materialList = CollStreamUtil.toList(courseMaterials, v -> {
                JSONObject material = JSONObject.from(v);
                material.put("specsList", materialSpecsMap.get(v.getId()));
                return material;
            });

            schoolCourseJson.put("courseMaterials", materialList);
        }

        return success(schoolCourseJson);
    }

    /**
     * 修改培训课程信息
     */
    @PreAuthorize("@ss.hasPermi('system:course:check')")
    @Log(title = "培训课程信息", businessType = BusinessType.UPDATE)
    @PostMapping("/check")
    public AjaxResult edit(@RequestBody JSONObject body) {
        Long id = body.getLong("id");
        Byte state = body.getByte("state");
        String remarks = body.getString("remarks");

        return toAjax(jyTrainingSchoolCourseService.checkTrainingSchoolCourse(id, state, remarks));
    }

}
